package com.atguigu.stgy.admin.service.impl;

import com.atguigu.stgy.admin.service.ApartmentFacilityService;
import com.atguigu.stgy.model.dto.ApartmentDTO;
import com.atguigu.stgy.model.entity.FacilityInfo;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.springframework.stereotype.Service;


import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.stgy.admin.mapper.ApartmentFacilityMapper;
import com.atguigu.stgy.model.entity.ApartmentFacility;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class ApartmentFacilityServiceImpl extends ServiceImpl<ApartmentFacilityMapper, ApartmentFacility> implements ApartmentFacilityService {
    public void batchSaveFacility(ApartmentDTO apartmentDTO, Long apartmentInfoId) {
      if(CollectionUtils.isEmpty(apartmentDTO.getFacilityInfoIds())){
          return;
      }
        //  apartment_info 公寓信息      facility_info: 配套信息表        apartment_facility： 公寓配套信息表  N:N
        //  ORM映射框架：  可以将对象转为关系保存到数据库表
        //将公寓配套id信息 转为一个个的公寓配套对象
        List<ApartmentFacility> apartmentFacilities = apartmentDTO.getFacilityInfoIds().stream()
                .map(facilityInfoId -> {
                    //将一个配套id转为一个公寓配套对象
                    ApartmentFacility apartmentFacility = new ApartmentFacility();
                    apartmentFacility.setApartmentId(apartmentInfoId);
                    apartmentFacility.setFacilityId(facilityInfoId);
                    return apartmentFacility;
                }).collect(Collectors.toList());

        this.saveBatch(apartmentFacilities);
    }

    @Override
    public List<FacilityInfo> getFacilityInfoByApartmentId(Long apartmentId) {
        return baseMapper.selectFacilityInfoByApartmentId(apartmentId);
    }

    @Override
    public void updateApartmentFacilityInfos(ApartmentDTO apartmentDTO) {
        this.remove(Wrappers.lambdaQuery(ApartmentFacility.class)
                .eq(ApartmentFacility::getApartmentId , apartmentDTO.getId()));
        //保存本次提交的配套列表
        this.batchSaveFacility(apartmentDTO , apartmentDTO.getId());
    }
}
